<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Tabs Example</title>
    <link rel="stylesheet" href="../highlight/styles/github-dark.css">
    <script src="../highlight/highlight.min.js"></script>
    <!-- <script>hljs.highlightAll();</script> -->
    <!-- 
./styles/a11y-dark.css
./styles/qtcreator-dark.css
./styles/github-dark.css
./styles/isbl-editor-dark.css
./styles/tokyo-night-dark.css
./styles/github-dark-dimmed.css
./styles/xt256.css
 -->
    <script>
        
code = `
#include "session_manager.h"
#include "nlohmann/json.hpp"
#include "../common/common.h"

namespace ArrowWebSocket
{

CSessionManager::CSessionManager()
{
}

CSessionManager::~CSessionManager()
{
    Deini();
}

void CSessionManager::Init(asio::io_context& ioContext)
{
    m_pTimer = new asio::steady_timer(ioContext);
}

void CSessionManager::Run()
{
    DoReadQueue();
    return;
}

void CSessionManager::Deini()
{
    if(m_pTimer != nullptr)
    {
        m_pTimer->cancel();
        delete m_pTimer;
        m_pTimer = nullptr;
    }
}

void CSessionManager::AddSession(SharedPtrISession pSession)
{
    if(m_setSessions.find(pSession) != m_setSessions.end())
        return;

    if(m_setMsgSrcInfo.size() > 0 )
    {
        std::string strTmpAllMsgSrcInfo;
        nlohmann::json j;
        for (auto& it : m_setMsgSrcInfo)
        {
            j.push_back(it);
        }
        strTmpAllMsgSrcInfo = j.dump();
        pSession->PutAllMsgSrcInfo(strTmpAllMsgSrcInfo);
    }

    m_setSessions.insert(pSession);
}

void CSessionManager::RemoveSession(SharedPtrISession pSession)
{
    m_setSessions.erase(pSession);
    if(m_setSessions.size() == 0)
    {
        m_setMsgSrcInfo.clear();
    }
}

void CSessionManager::PutMsg(const SharedPtrMsg& pMsg)
{
    m_msgQueue.Push(pMsg);
}

void CSessionManager::DoReadQueue()
{
    // if (m_msgQueue.Empty())
    // {
    //     // 启动定时器 10毫秒后再次调用
    //     m_pTimer->expires_after(std::chrono::milliseconds(10));
    //     m_pTimer->async_wait([this](beast::error_code ec) {
    //         if (!ec)
    //         {
    //             DoReadQueue();
    //         }
    //     });
    //     return;
    // }
    // SharedPtrMsg pMsg;
    // if( false == m_msgQueue.Pop(pMsg))
    // {
    //     return;
    // }

    // auto it = m_setMsgSrcInfo.find(pMsg->SrcInfo());
    // if(it == m_setMsgSrcInfo.end())
    // {
    //     m_setMsgSrcInfo.insert(pMsg->SrcInfo());
    //     nlohmann::json j;
    //     j["msg_type"] = static_cast<int32_t>(EmMsgType::AllMsgSrcInfo);
    //     for (auto& it : m_setMsgSrcInfo)
    //     {
    //         j["msg_src_info"].push_back(it);
    //     }
    //     std::string strtmp = j.dump();

    //     for (auto& it : m_setSessions)
    //     {
    //         it->PutAllMsgSrcInfo(strtmp);
    //     }
    // }

    // for (auto& it : m_setSessions)
    // {
    //     it->PutMsg(pMsg);
    // }    
    // DoReadQueue();
}

int32_t CSessionManager::Count()
{
    return m_setSessions.size();
}

} // namespace ArrowWebSocket

`;

  // 定义OneTabData结构体
  class OneTabData {
    constructor(name, code) {
        this.tabName = name;
        this.tabData = code;
    }
}

// 定义CodeViewData结构体
class CodeViewData {
    constructor() {
        this.activeTabName = "";
        this.allTabData = [];
    }

    saveStorage()
    {
        localStorage.setItem("activeTabName", this.activeTabName);
        localStorage.setItem("allTabData", JSON.stringify(this.allTabData));
    }

    loadStorage()
    {
        this.activeTabName = localStorage.getItem("activeTabName");
        this.allTabData = JSON.parse(localStorage.getItem("allTabData"));
        if(this.allTabData == null)
        {
            this.activeTabName = "";
            this.allTabData = [];
        }
        console.log(JSON.stringify(this));
    }

    setActive(tabName)
    {
        this.activeTabName = tabName;
    }

    addTabData(tabData) {
        this.allTabData.push(tabData);
    }

    removeTabData(tabName) {
        var index = -1;
        for(let i = 0; i < this.allTabData.length; ++i){
            if(this.allTabData[i].tabName == tabName)
                index = i;
        }
        if (index > -1) {
            this.allTabData.splice(index, 1);
        }
        if(this.allTabData.length == 0)
        {
            this.activeTabName = "";
        }
    }
}
let codeViewData = new CodeViewData();

// window.onbeforeunload = function()
// {
//     codeViewData.saveStorage();
// }

// window.onload = function()
// {
//     codeViewData.loadStorage();
//     for(let i = 0; i < codeViewData.allTabData.length; ++i)
//     {
//         createTab(codeViewData.allTabData[i].tabName, codeViewData.allTabData[i].tabData);
//     }
//     activateTab(codeViewData.activeTabName);
// }

function toggleLeftBar() {
    var container = document.getElementById('left-bar-container');
    if(container == null)
        console.log("container is null");
    container.classList.toggle('hide');
    var toggleBtn = document.getElementById('toggle-left-bar-btn');
    toggleBtn.innerHTML = container.classList.contains('hide') ? 'Show' : 'Hide';
}

function createOrActivateTab(tabName) {

    var existingTab = document.getElementById(tabName);
    var existingTabContent = document.getElementById(tabName + '-content');

    if (existingTab) {
        activateTab(tabName);
    } else {
        createTab(tabName, code);
        codeViewData.addTabData(new OneTabData(tabName, code));
        activateTab(tabName);
    }
}

function createTab(tabName, tabData)
{
    var tabs = document.getElementById('tabs-container');
    var viewContainer = document.getElementById('view-container');

    var newTab = document.createElement('div');
    newTab.className = 'tab';
    newTab.id = tabName;
    newTab.innerHTML = `${tabName} <span class="close-btn" onclick="closeTab(event, '${tabName}')">x</span>`;
    newTab.onclick = function() { activateTab(tabName); };

    var view = document.createElement('div');
    view.className = 'view';
    view.id = tabName + '-content';
    view.innerHTML = `<pre><code class="cpp">${tabName}${tabData}</code></pre>`;
    view.querySelectorAll('pre code').forEach((block) => {
        hljs.highlightBlock(block);
    });

    tabs.appendChild(newTab);
    viewContainer.appendChild(view);
}

function activateTab(tabName) {

    tab = document.getElementById(tabName);
    view = document.getElementById(tabName + "-content")

    var i, tablinks, tabcontents;
    tablinks = document.getElementsByClassName('tab');
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].classList.remove('active');
    }

    tabcontents = document.getElementsByClassName('view');
    for (i = 0; i < tabcontents.length; i++) {
        tabcontents[i].classList.remove('active');
    }

    tab.classList.add('active');
    view.classList.add('active');

    codeViewData.setActive(tabName);

    // console.log(JSON.stringify(codeViewData));
}

function closeTab(event, tabName) {
    event.stopPropagation();
    var tab = document.getElementById(tabName);
    var tabContent = document.getElementById(tabName + '-content');
    tab.remove();
    tabContent.remove();

    codeViewData.removeTabData(tabName);
    console.log(JSON.stringify(codeViewData));

    var tabs = document.getElementsByClassName('tab');
    if (tabs.length > 0) {
        // activateTab(tabs[0], document.getElementById(tabs[0].id + '-content'), tabs[0].id);
        activateTab(tabs[0].id);
    }
}
    </script>

    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, sans-serif;
        }
        
        .main-frame
        {
            display: flex;
            flex-direction: column;
            background-color: green;
            width: 100%;
            height: 100%;
        }
        
        .top-bar {
            display: flex;
            flex-direction: row;
            flex: 0 0 25px;
            background-color: steelblue;
            color: white;
           
            align-items: center;
            padding: 0 10px;
            box-sizing: border-box;
            z-index: 1000;
        }
        
        .child-frame
        {
            display: flex;
            flex-direction: row;
            flex : 1;
            background-color: black;
            color: white;
            width: 100%;
            height: calc(100% - 25px);
        }
        
        .left-bar
        {
            flex: 0 0 250px;
            background-color: #181818;
            border: 1px solid #2B2B2B;
            color: white;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            padding-top: 10px;
            padding-left: 10px;
        }
        
        .path-item
        {
            padding-top: 5px;
            border: 1px solid #2B2B2B;
            /* background-color:black; */
        }
        
        .view-frame
        {
            flex: 1;
            display: flex;
            flex-direction: column;
            /*overflow-y: auto;*/
        }
        
        .tabs {
            flex : 0 0 35px;
            border: 1px solid #2B2B2B;
            display: flex;
            flex-direction: row;
        }
        
        .tab {
            padding: 10px;
            cursor: pointer;
            border: 1px solid #2B2B2B;
            border-bottom: none;
            margin-right: 5px;
            position: relative;
            display: flex;
            align-items: center;
        }
        
        .tab .close-btn {
            margin-left: 10px;
            cursor: pointer;
            color: red;
            font-weight: bold;
        }
        
        .tab.active {
            background-color: #606060;
            font-weight: bold;
        }
        
        .views {
            flex: 1;
            background-color: #0d1117;
            display: flex;
            overflow: hidden;
            border: 1px solid #2B2B2B;
        }
        
        .view {
            flex: 1;
            overflow-y: auto;
            display: none;
            background-color: #0d1117;
            border: 1px solid #2B2B2B;
        }
        
        .view.active {
            display: block;
        }
        
        .hide {
            display: none;
        }
        
        pre
        {
            padding-left: 20px;
            padding-top: 0px;
        }
    </style>
</head>
<body>
    <div class="main-frame">
        <div class="top-bar">
            <button onclick="toggleLeftBar()" id="toggle-left-bar-btn">Hide</button>
            <span style="margin-left: 10px;">This is the top bar</span>
        </div>
        <div class="child-frame">
            <div class="left-bar"  id="left-bar-container">
                <div class="path-item" onclick="createOrActivateTab('index.html')">index.html</div>
                <div class="path-item" onclick="createOrActivateTab('styles.css')">styles.css</div>
                <div class="path-item" onclick="createOrActivateTab('script.js')">script.js</div>
            </div>
            <div class="view-frame">
                <div class="tabs" id="tabs-container">
                </div>
                <div class="views" id="view-container">
                </div>
            </div>
        </div>
</div>
</body>
</html>
